package com.example.taco_message_receive.messing.rabbitmq;

import com.example.taco_message_receive.messing.Order;
import org.aspectj.weaver.ast.Or;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Component;

/*
   receive()接收消息
   receiveAndConvert（）接受由消息转换成的对象
   receiveAndConvert（ParameterizedTypeReference）接受由消息转换成类型安全的对象
 */
@Component
public class RabbitOrderReceiver {


    private RabbitTemplate rabbit;

    private MessageConverter converter;

    @Autowired
    public RabbitOrderReceiver(RabbitTemplate rabbit, MessageConverter converter) {
        this.rabbit = rabbit;
        this.converter = converter;
    }

//    public Order receiveOrder(){
//        Message message = rabbit.receive("tacocloud.order",30000);
//        return message != null ? (Order) converter.fromMessage(message):null;
//    }

    public Order receiveOrder() {
        return (Order) rabbit.receiveAndConvert("tacocloud.order,queue");
    }

    //传入一个ParameterizedTypeReference就不需要强转 如果使用这个，消息转换器必须实现SmartMessageConverter
    public Order receiveOrder_() {
        return rabbit.receiveAndConvert("tacocloud.order,queue", new ParameterizedTypeReference<Order>() {
        });
    }
}
